<template>

  <el-input v-if="searchType=='input'" clearable style="width: 250px;" class="filter-item" clearable
            :placeholder="placeholder" v-model="bindValue">
  </el-input>
  <el-upload v-else-if="searchType=='img'"
             :headers="getHeaders()"
             :action="getBaseUrl()"
             :show-file-list="false"
             :on-success="uploadPicUrl"
             class="avatar-uploader"
             accept=".jpg,.jpeg,.png,.gif">
    <img v-if="bindValue" :src="bindValue"
         :style="'width: '+widthValue+'px;height: '+heightValue+'px;display: block'">
    <i v-else class="el-icon-plus "
       :style="'font-size: 28px;color: #8c939d;width: '+widthValue+'px;height: '+heightValue+'px;line-height: '+heightValue+'px;text-align: center;'"/>
  </el-upload>

  <el-select v-else-if="searchType=='select'&&dataLoaded&&load==undefined" v-model="bindValue" clearable
             class="filter-item"
             :placeholder="placeholder">
    <el-option v-for="item in options" :key="item.value" :label="item.label"
               :value="item.value"/>
  </el-select>
  <el-select v-else-if="searchType=='select'&&load==undefined&&!dataLoaded" v-model="bindValue" clearable
             class="filter-item"
             :placeholder="placeholder">
    <el-option v-for="item in options" :key="item.value" :label="item.label"
               :value="item.value"/>
  </el-select>
  <el-select v-else-if="searchType=='select'&&dataLoaded&&load!=undefined" v-model="bindValue" class="filter-item"
             filterable
             remote
             reserve-keyword
             @clear="getSelectRemoteData"
             :remote-method="getSelectRemoteData"
             clearable :placeholder="placeholder">
    <el-option
      v-for="item in remoteOptions"
      :key="item.value"
      :label="item.label"
      :value="item.value">
    </el-option>
  </el-select>
  <el-select v-else-if="searchType=='select'&&load!=undefined&&!dataLoaded" v-model="bindValue" class="filter-item"
             filterable
             remote
             reserve-keyword
             @clear="getSelectRemoteData"
             :remote-method="getSelectRemoteData"
             clearable :placeholder="placeholder">
    <el-option
      v-for="item in remoteOptions"
      :key="item.value"
      :label="item.label"
      :value="item.value">
    </el-option>
  </el-select>

  <el-cascader v-else-if="searchType=='cas'&&dataLoaded" :options="options" v-model="casPath" :props="props" clearable
               :placeholder="placeholder" @change="handleChange"></el-cascader>
  <el-cascader v-else-if="searchType=='cas'&&!dataLoaded" :options="options" v-model="casPath" :props="props" clearable
               :placeholder="placeholder" @change="handleChange"></el-cascader>

  <el-date-picker v-else-if="searchType=='date'" v-model="bindValue" class="filter-item" style="width: 220px;"
                  type="datetime"
                  :placeholder="placeholder" value-format="yyyy-MM-dd HH:mm:ss"
                  format="yyyy-MM-dd HH:mm:ss"></el-date-picker>
</template>

<style scoped>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #20a0ff;
  }

  .picUrl-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 120px;
    height: 120px;
    line-height: 120px;
    text-align: center;
  }

  .picUrl {
    width: 80px;
    height: 80px;
    display: block;
  }

  .el-form-item .el-input {
    width: 320px;
  }

  .el-form-item .el-select {
    width: 320px;
  }

  .el-form-item .el-cascader {
    width: 320px;
  }
</style>
<script>
  import { fetchList } from '@/api/dict'
  import { setMapStorage, getMapStore } from '@/util/store'
  import { validatenull } from '@/util/validate'
  import { recursiveData, multipleChoice } from '@/util/casUtils'
  import { uploadPath } from '@/api/storage'  //上传图片
  import { getToken } from '@/util/auth'

  export default {
    name: 'globalGeneralTemplate',
    model: {
      prop: 'modelVal',//指向props的参数名
      event: 'bindModelEvent'//事件名称
    },
    searchType: {
      prop: 'type',//指向props的参数名
      event: 'typeEvent'//事件名称
    },
    props: {
      'modelVal': '',
      'placeholder': undefined,
      'type': undefined,
      'config': undefined,
      'prop': undefined,
      'load': undefined,
      'props': undefined,
      'width': undefined,
      'height': undefined
    },
    data() {
      return {
        listLoading: true,
        listQuery: {
          page: 1,
          limit: 50,
          module: this.config.module,
          componentName: this.config.componentName,
          fieldName: this.prop
        },
        listRemoteQuery: {
          page: 1,
          limit: 50
        },
        options: [],
        bindValue: this.modelVal,
        searchType: this.type,
        storageKey: this.config.module + this.config.componentName + this.prop,
        casStorageKey: 'cas:' + this.config.module + this.config.componentName + this.prop,
        casPath: [],
        dataLoaded: false,
        remoteOptions: [],
        widthValue: this.width,
        heightValue: this.height
      }
    },
    created() {

      if (this.widthValue == undefined) {
        this.widthValue = '60'
      }

      if (this.heightValue == undefined) {
        this.heightValue = '60'
      }

      if (this.prop == undefined && this.searchType == undefined) {
        this.searchType = 'input'
      }

      if (this.searchType == 'select' && this.load == undefined) {
        var obj = getMapStore(this.storageKey)
        let newObj = JSON.parse(obj)//深度复制对象
        if (validatenull(newObj)) {
          this.getList()
        } else {
          this.options = newObj
          this.dataLoaded = true
        }
      }

      if (this.searchType == 'select' && this.load != undefined) {

        if (this.bindValue == undefined || this.bindValue == null) {
          this.bindValue = ''
        }

        if (this.bindValue != undefined) {
          this.bindValue = this.bindValue.toString()
        }

        this.getSelectRemoteData('')
      }

      if (this.searchType == 'cas') {
        this.options.push({ 'label': '父级栏目', 'value': '0', 'children': undefined })
        var obj = getMapStore(this.casStorageKey)
        let newObj = JSON.parse(obj)//深度复制对象
        if (validatenull(newObj) || null == newObj) {
          this.getCasData()
        } else {

          this.options = newObj
          if (this.bindValue != undefined) {
            recursiveData(this.options, this.casPath, [], this.bindValue.toString())
          }
          this.dataLoaded = true
          //进行延时数据更新缓存
          this.getCasData()
        }
      }

    },
    filters: {},
    watch: {
      //监听值变化，再赋值给modelVal
      bindValue(value) {
        this.$emit('bindModelEvent', value)
      },
      searchType(value) {
        this.$emit('typeEvent', value)
      }
    },
    methods: {
      getHeaders() {
        var headers = {
          Authorization: 'Bearer ' + getToken()
        }
        return headers
      },
      getBaseUrl() {
        return uploadPath
      },
      uploadPicUrl(response) {
        this.bindValue = response.data.url
      },
      getSelectRemoteData(query) {
        this.listRemoteQuery.label = query
        this.load(this.listRemoteQuery).then((response) => {
          var data = response.data.data
          if (null != data && data.length > 0) {
            this.remoteOptions = data
          } else {
            this.remoteOptions = []
          }
          this.dataLoaded = true
        })
      },
      getCasData() {
        this.load().then((response) => {
            var data = response.data.data
            if (null != data && data.length > 0) {
              this.options[0].children = data
              setMapStorage(this.casStorageKey, this.options)
              if (this.bindValue != undefined) {
                this.casPath = []
                recursiveData(this.options, this.casPath, [], this.bindValue.toString())
              }
            }
            this.dataLoaded = true
          }
        )
      },
      getList() {
        this.listLoading = false
        this.listQuery.orderByField = 'create_time'
        this.listQuery.isAsc = false
        this.listQuery.fieldName = this.prop
        this.listQuery.module = JSON.stringify(this.config.module)
        this.listQuery.componentName = JSON.stringify(this.config.componentName)
        fetchList(this.listQuery).then(response => {
          var data = response.data.data.records
          if (data.length > 0) {
            data.forEach(d => {
              this.options.push({
                value: d.value,
                label: d.name
              })
            })
            setMapStorage(this.storageKey, this.options)
          } else {
            this.options = []
          }
          this.dataLoaded = true
        })
      },
      handleChange(value) {
        if (value.length > 0) {
          this.casPath = value
          this.bindValue = value[value.length - 1]
        } else {
          this.casPath = []
          this.bindValue = undefined
        }
      }
    }
  }
</script>
<style>

</style>
